const router = require("@koa/router")()
const mongo = require("../../model/api/Like");
const assert = require("http-assert");
const { localTime } = require("../../utils/index");

router.get("/", async (ctx) => {
  ctx.body = "欢迎来到点赞模块"
})


router.post("/click", async (ctx, next) => {
  try {
    const { love, loved } = ctx.request.body;
    assert(love, 402, "缺少参数")
    assert(loved, 402, "缺少参数")
    /* 先找有么有这个人,没有直接点赞 */
    const res = await mongo.find({ love });
    const res2 = await mongo.find({ love, loved });
    if (res.length <= 0 || res2.length <= 0) {
      const res = await mongo.create({ love, loved, time: localTime() });
      ctx.body = {
        status: 0,
        message: "点赞成功",
        data: res
      }
      console.log(res)
    } else {
      ctx.body = {
        status: -1,
        message: "您已经点过赞了",
        data: res
      }
    }


  } catch (error) {
    console.log(error)
    ctx.body = {
      status: -1,
      message: error.message,
      data: null
    }
  }
})


router.post("/sick", async (ctx) => {
  try {
    const { user, mine } = ctx.request.body;
    assert(mine, 402, "缺少参数")
    assert(user, 402, "缺少参数")
    const res = await mongo.findOneAndUpdate({ user }, { $pull: { friends: mine }, $inc: { count: -1 } }, { new: true });
    if (res) {
      ctx.body = {
        status: 0,
        message: "success",
        data: null
      }
    } else {
      ctx.body = {
        status: -1,
        message: "fail",
        data: null
      }
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      status: -1,
      message: error.message,
      data: null
    }
  }

})

module.exports = router